#coding=utf-8
from uliweb.orm import *
import datetime
from uliweb.utils.common import get_var

def get_hexdigest(algorithm, salt, raw_password):
    """
    Returns a string of the hexdigest of the given plaintext password and salt
    using the given algorithm ('md5', 'sha1' or 'crypt').
    """
    if algorithm == 'crypt':
        try:
            import crypt
        except ImportError:
            raise ValueError('"crypt" password algorithm not supported in this environment')
        return crypt.crypt(raw_password, salt)
    # The rest of the supported algorithms are supported by hashlib, but
    # hashlib is only available in Python 2.5.
    try:
        import hashlib
    except ImportError:
        if algorithm == 'md5':
            import md5
            return md5.new(salt + raw_password).hexdigest()
        elif algorithm == 'sha1':
            import sha
            return sha.new(salt + raw_password).hexdigest()
    else:
        if algorithm == 'md5':
            return hashlib.md5(salt + raw_password).hexdigest()
        elif algorithm == 'sha1':
            return hashlib.sha1(salt + raw_password).hexdigest()
    raise ValueError("Got unknown password algorithm type in password.")

def check_password(raw_password, enc_password):
    """
    Returns a boolean of whether the raw_password was correct. Handles
    encryption formats behind the scenes.
    """
    algo, salt, hsh = enc_password.split('$')
    return hsh == get_hexdigest(algo, salt, raw_password)

from uliweb.utils.common import get_var
class User(Model):
    username = Field(str, verbose_name="用户名", max_length=30, required=True, unique=True, index=True, nullable=False)
    email = Field(str, verbose_name="邮箱", max_length=40)
    telphone = Field(str, verbose_name="电话", max_length=15)
    mobile = Field(str, verbose_name="手机", max_length=11)
    password = Field(str, max_length=128, nullable=False)
    is_superuser = Field(bool, verbose_name="超级用户")
    department = Field(CHAR, verbose_name="部门分类", max_length=1, choices=get_var('PARA/DEPARTMENT'), nullable=True)
    kfzx = Reference('kfzx', verbose_name="部门名称", collection_name='kfzx_users')
    tx = Reference('tx', verbose_name="条线", collection_name='tx_users')
    is_manager = Field(bool, verbose_name="管理员")
    is_gm = Field(bool, verbose_name="主管")
    last_login = Field(datetime.datetime, verbose_name="上次登录时间")
    image = Field(FILE, verbose_name="头像", max_length=255)
    manager = SelfReference(collection_name='members')
    nickname = Field(str, verbose_name="显示名称", max_length=30)
    deleted = Field(bool, verbose_name="删除标志")
    
    def set_password(self, raw_password):
        import random
        algo = 'sha1'
        salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
        hsh = get_hexdigest(algo, salt, raw_password)
        self.password = '%s$%s$%s' % (algo, salt, hsh)
        self.save()
    
    def check_password(self, raw_password):
        """
        Returns a boolean of whether the raw_password was correct. Handles
        encryption formats behind the scenes.
        """
        return check_password(raw_password, self.password)
    
    def get_image_url(self):
        from uliweb.contrib.upload import get_href
        from uliweb.contrib.staticfiles import url_for_static
        
        if self.image:
            return get_href(self.image)
        else:
            return url_for_static('images/user%dx%d.jpg' % (50, 50))
        
    def get_default_image_url(self, size=50):
        from uliweb.contrib.staticfiles import url_for_static
        return url_for_static('images/user%dx%d.jpg' % (size, size))
    
    def __unicode__(self):
        return self.nickname or self.username
    
    class Meta:
        display_field = 'username'
        
    class DetailView:
        fields = ('username', 'nickname', 'department', 'kfzx', 'tx', 'email', 'telphone', 'mobile',
            'is_superuser', 'is_gm', 'is_manager')
    
    class EditForm:
        fields = ('username', 'nickname', 'email', 'telphone', 'mobile')
        
    class Table:
        fields = [
            {'name':'username'},
            {'name':'nickname'},
            {'name':'department'},
            {'name':'kfzx'},
            {'name':'tx'},
            {'name':'email'},
            {'name':'telphone'},
            {'name':'mobile'},
            {'name':'is_superuser', 'width':60},
            {'name':'is_gm', 'width':60},
            {'name':'is_manager', 'width':60},
        ]
        
def kfzx_gm(user):
    """
    判断用户是否是开发中心主管
    """
    return bool(user and user.is_gm and (user.department in ('2', '3')))

def sys_manager(user, system_id):
    """
    判断用户是否是系统管理员
    """
    from uliweb.orm import get_model
    System = get_model('system')
    obj = System.get(int(system_id))
    return bool(user and (obj._manager_ ==user.id or obj.users.has(user.id)))

def test_gm(user):
    """
    判断用户是否是测试主管
    """
    return bool(user and user.is_gm and user.department=='3')